import streamlit as st
import pandas as pd
import numpy as np
import os
import datetime
import json
import requests
import time

st.text('默认模式')
# =====================================Markdown========================================================
# markdown
st.markdown('Streamlit Demo')

# 设置网页标题
st.title('一个傻瓜式构建可视化 web的 Python 神器 -- streamlit')

# 展示一级标题
st.header('1. 安装')

st.text('和安装其他包一样，安装 streamlit 非常简单，一条命令即可')
code1 = '''pip3 install streamlit'''
st.code(code1, language='bash')

# 展示一级标题
st.header('2. 使用')

# 展示二级标题
st.subheader('2.1 生成 Markdown 文档')

# 纯文本
st.text('导入 streamlit 后，就可以直接使用 st.markdown() 初始化')

# 展示代码，有高亮效果
code2 = '''import streamlit as st
st.markdown('Streamlit Demo')'''
st.code(code2, language='python')

# =====================================表格========================================================
df = pd.DataFrame(
    np.random.randn(10, 5),
    columns=('第%d列' % (i + 1) for i in range(5))
)

st.dataframe(df.style.highlight_max(axis=0))

# =====================================监控组件========================================================
col1, col2, col3 = st.columns(3)
col1.metric("Temperature", "70 °F", "1.2 °F")
col2.metric("Wind", "9 mph", "-8%")
col3.metric("Humidity", "86%", "4%")

# =====================================折线图========================================================
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=['a', 'b', 'c'])

st.line_chart(chart_data)

# =====================================面积图========================================================
chart_data = pd.DataFrame(
    np.random.randn(20, 3),
    columns=['a', 'b', 'c'])

st.area_chart(chart_data)

# =====================================柱状图========================================================
chart_data = pd.DataFrame(
    np.random.randn(50, 3),
    columns=["a", "b", "c"])
st.bar_chart(chart_data)

# =====================================地图========================================================
df = pd.DataFrame(
    np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
    columns=['lat', 'lon']
)
st.map(df)

# =====================================留言板========================================================
# Message board
st.markdown("---")
st.header("留言板")

CSV_FILE = "messages.csv"

# Load or create a DataFrame to store messages
if os.path.exists(CSV_FILE):
    messages_df = pd.read_csv(CSV_FILE)
else:
    messages_df = pd.DataFrame(columns=["timestamp", "username", "message"])

# Display existing messages
st.write(messages_df[["timestamp", "username", "message"]].sort_values(by="timestamp", ascending=False))

# Input form for new messages
with st.form(key="message_form"):
    username = st.text_input("用户名")
    message = st.text_input("留言内容")
    submit_button = st.form_submit_button("提交留言")

# Save new messages to the DataFrame and CSV file
if submit_button and username and message:
    new_message = pd.DataFrame({"timestamp": [datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
                                "username": [username],
                                "message": [message]})
    messages_df = pd.concat([messages_df, new_message], ignore_index=True)
    messages_df.to_csv(CSV_FILE, index=False)

# =====================================inscode版chatgpt========================================================

INSCODE_API_KEY = os.getenv("INSCODE_API_KEY")
API_URL = "https://inscode-api.csdn.net/api/v1/gpt/"


def send_question(question):
    body = {
        "messages": [{"role": "user", "content": question}],
        "apikey": INSCODE_API_KEY,
    }

    response = requests.post(API_URL, json=body)
    if response.status_code == 200:
        if response.text:
            try:
                response_parts = response.text.strip().split("\n")[:-1]
                full_response = ""
                for part in response_parts:
                    if part.startswith("data:"):
                        json_part = json.loads(part[5:])
                        content = json_part["choices"][0]["delta"].get("content", '')
                        full_response += content
                return full_response
            except json.JSONDecodeError as e:
                st.write("Failed to parse JSON response:")
                st.write(response.text)
                st.write("Error details:", str(e))
                return None
        else:
            st.write("Received empty response from the API.")
            return None
    else:
        st.write("Error: ", response.status_code, response.text)
        return None


st.title("Streamlit ChatGPT")

question = st.text_input("输入问题:")
if question and st.button("发送"):
    response_data = send_question(question)
    if response_data:
        answer = response_data
        display = st.empty()
        text = ""
        for char in answer:
            text += char
            display.markdown(f"{text}", unsafe_allow_html=True)
            time.sleep(0.1)
    else:
        st.write("No response received from the API.")
